package com.jrx.anytxn.common.uitl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Random;

public class StartCommand {
    private static Logger logger = LoggerFactory.getLogger(StartCommand.class);

    public static String[] getStartServerArgs(String[] args) {
        String port = "";
        Boolean isServerPort = false;
        if (null != args) {
            for (String arg : args) {
                if (StringUtils.isNotBlank(arg) && arg.startsWith("--server.port")) {
                    isServerPort=true;
                    port = arg.split("=")[1];
                    logger.info("当前端口号:{}",port);
                    break;
                }
            }
        }
        if(StringUtils.isNotBlank(port) && isPortUsing(Integer.parseInt(port))){
            port = String.valueOf(getAvailablePort());
            String serverPort = "--server.port="+port;
            logger.info("当前端口号:{}",port);
            if (isServerPort) {
                for (int i=0;i<args.length;i++) {
                    if (StringUtils.isNotBlank(args[i]) && args[i].startsWith("--server.port")) {
                        args[i] = serverPort;
                        break;
                    }
                }
            }else{
                String[] newArgs  = Arrays.copyOf(args,args.length+1);
                newArgs[args.length] = serverPort;
                return newArgs;
            }
        }
        return args;
    }

    private static int getAvailablePort() {
        int max = 65535;
        int min = 2000;
        Random random = new Random();
        int port = random.nextInt(max)%(max-min+1) + min;
        if (isPortUsing(port)) {
            return getAvailablePort();
        } else {
            return port;
        }
    }

    private static boolean isPortUsing(int port)  {
        logger.info("检查端口号是否被占用: {}", port);
        boolean flag = false;
        Socket socket= null;
        try {
            InetAddress theAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(theAddress, port);
            flag = true;
            logger.info("端口号被占用: {}", port);
        }  catch (Exception e) {
            logger.info("端口号不被占用: {}", port);
        }finally {
            if(null != socket && !socket.isClosed()){
                try {
                    socket.close();
                    logger.info("关闭端口检查连接: {}", port);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return flag;
    }
}
